<template>
  <el-dialog
    :model-value="isShowDialog"
    :title="title"
    :width="width"
    min-width="500px"
    :close-on-click-modal="false"
    :before-close="handleModalClose"
  >
    <div class="main_block">
      <div class="header flex_block">
        <div class="header_item flex_block">
          <div class="text">测试时间：</div>
          <el-date-picker
            v-model="params.time"
            type="datetime"
            placeholder="不填默认立即执行"
            :clearable="false"
            :show-now="false"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </div>
        <div class="header_item flex_block">
          <div class="text">并发数：</div>
          <el-input
            min="1"
            @blur="handleBlurConcurrency"
            v-model.trim="params.concurrency"
            type="number"
            placeholder="请输入并发数"
            style="min-width: 100px"
          ></el-input>
        </div>
        <!-- <div class="header_item flex_block" >
          <div class="text">优先级：</div>
          <el-select
            v-model="params.priority"
            @change="handleChangePriority"
            multiple
            placeholder="请选择优先级"
            style="min-width: 160px"
          >
            <el-option
              class="select_item"
              v-for="item in priority_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div> -->
        <div class="header_item flex_block">
          <div class="text">执行环境：</div>
          <el-select
            v-model="params.environment"
            placeholder="请选择执行环境"
            style="min-width: 160px"
          >
            <el-option
              class="select_item"
              v-for="item in environmentList"
              :key="item.envName"
              :label="item.envName"
              :value="item.envName"
            />
          </el-select>
        </div>
      </div>
      <div class="table_block">
        <el-table
          :data="tableData"
          border
          :style="{ height: 'calc(100vh - 420px)' }"
        >
          <el-table-column type="index" label="序号" width="80px" />
          <el-table-column prop="name" label="用例名" />
          <el-table-column prop="severity" label="优先级" />
          <el-table-column
            prop="caseData"
            label="测试数据"
            min-width="180"
            align="center"
          >
            <template #default="{ row }">
              <el-select
                v-model="row.isDefaultId"
                placeholder="测试数据"
                size="small"
                style="min-width: 100px"
              >
                <el-option
                  class="select_item"
                  v-for="item in row.dataList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleModalClose">取消</el-button>
        <el-button
          type="primary"
          :loading="but_loading"
          @click="handleModalConfirm"
        >
          执行
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { formatTime } from "@/utils/index.js";
import { PriorityAllList } from "@/api/test_case.js";
import { AdminExampleExecuteTestExampleBatch } from "@/api/test_case";

import { AdminEnvironmentList } from "@/api/settings.js";
import { ElMessage } from "element-plus";

const route = useRoute();

const props = defineProps({
  isShowDialog: { type: Boolean, default: false },
  title: { type: String, default: "发起测试" },
  width: { type: [String, Number], default: "60vw" },
  list: { type: Array, default: () => [] },
});
const environmentList = ref([]); //环境

const $emit = defineEmits(["close", "confirm"]); // 接受父组件传递的 方法

const params = reactive({
  // 顶部可选 参数
  time: formatTime(), //默认当前时间
  concurrency: 1,
  priority: [],
  environment: null,
});
let originally_environment = null; //备份初始数据（执行环境）默认第一个
const but_loading = ref(false);
const tableData = ref([]); //table数据
const flatCaseData = ref([]); //备份列表数据

// 组件加载时
onMounted(() => {
  getEnvironmentData();
});

watch(
  () => props.list,
  (val) => {
    if (val && val.length && val.length > 0) {
      let list = JSON.parse(JSON.stringify(val));
      list.forEach((item) => {
        if (item.dataList && item.dataList.length) {
          console.log("item.dataList", item.dataList);
          console.log("item.data", item.data);
          // 当前的测试数据ID跟数据id对比
          const file = item.dataList.find(
            (value) =>
              value.examplePath == item.data.examplePath &&
              value.name == item.data.name
          );
          console.log("filefilefilefile", file);

          item.isDefaultId = file?.id || "";
        } else {
          item.dataList = [];
        }
      });
      console.log("tableData.value", list);
      tableData.value = list;
    }
  },
  { immediate: true, deep: true }
);
// 监听 isShowDialog 变为 true 时初始化参数
watch(
  () => props.isShowDialog,
  (newVal) => {
    if (newVal) {
      params.time = ''; // 默认当前时间
      params.concurrency = 1;
      params.priority = [];
      params.environment = originally_environment;
      tableData.value = flatCaseData.value;
    }
  },
  { immediate: true }
);
// 并发数只能是正整数
const handleBlurConcurrency = () => {
  params.concurrency = parseInt(params.concurrency);
  if (params.concurrency <= 0 || isNaN(params.concurrency)) {
    params.concurrency = 1;
  }
};

//获取执行环境数据
const getEnvironmentData = () => {
  let obj = {
    pageNum: 1,
    pageSize: 2000,
    queryParams: {},
  };
  AdminEnvironmentList(obj).then((res) => {
    environmentList.value = res.list || [];
    console.log("res", environmentList.value);
    if (route.query.envName) {
      console.log("route.query.envName", route.query.envName);
      originally_environment = route.query.envName;
      params.environment = route.query.envName;
    } else if (environmentList.value.length > 0) {
      const isDefault = environmentList.value.find((val) => val.default);
      if (isDefault) {
        params.environment = isDefault.envName;
        originally_environment = isDefault.envName;
      } else {
        params.environment = environmentList.value[0].envName;
        originally_environment = environmentList.value[0].envName;
      }
    }
  });
};

// 关闭弹窗
const handleModalClose = () => {
  $emit("close");
};

const handleModalConfirm = () => {
  if (!params.concurrency) {
    return ElMessage.warning("请选择并发数");
  }
  if (!params.environment) {
    return ElMessage.warning("请选择执行环境");
  }
  if (tableData.value.length === 0) {
    return ElMessage.warning("请最少选择一个用例");
  }
  // if (params.time) {
  //   // 匹配最后一个 ":数字" 并替换为 ":00"
  //   params.time = params.time.replace(/:\d{2}$/, ":00");
  // }
  // if (params.time < formatTime()) {
  //   return ElMessage.warning("执行时间不能早于当前时间");
  // }
  for (let i = 0; i < tableData.value.length; i++) {
    // 如果没选测试数据，就不让提交，提示需要选择
    if (!tableData.value[i].dataName) {
      return ElMessage.warning(`${tableData.value[i].name} 测试数据文件丢失`);
    }
  }

  // $emit("confirm",tableData.value,params);
  // handleModalClose()
  let list = JSON.parse(JSON.stringify(tableData.value));
  let exampleList = [];
  list.forEach((item) => {
    exampleList.push({
      id: item.id,
      title: item.title,
      story: item.story,
      name: item.name,
      scene: item.scene,
      severity: item.severity,
      description: item.description,
      step: item.step,
      code: item.code,
      data: item.data,
    });
  });
  let obj = {
    executeTime: params.time,
    concNum: params.concurrency + "",
    envName: params.environment,
    exampleList: exampleList,
  };
  but_loading.value = true;
  AdminExampleExecuteTestExampleBatch(obj)
    .then((res) => {
      ElMessage.success(
        "测试任务已启动，可到【测试记录】中查看本次测试状态和测试结果"
      );
      handleModalClose();
    })
    .finally((res) => {
      but_loading.value = false;
    });
};
</script>

<style scoped lang="scss">
.header {
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  .header_item {
    margin-bottom: 5px;
    align-items: center;
    .text {
      white-space: nowrap;
      min-width: 80px;
      text-align: center;
    }
  }
}
.table_block {
  margin-top: 10px;
}
</style>
